package org.robert.export_client.file;

import com.robert.common.commonutil.bean.vo.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @Description 文件下载
 * @Author robert
 * @Date 2024/1/14 21:25
 **/
@Slf4j
public class FileDownloadService {


    public ResultData download(String path, String fileName, HttpServletResponse response){
        File file = new File(path + fileName);
        if (!file.exists()){
            return ResultData.error("文件不存在");
        }
        byte[] bytes = new byte[1024];
        BufferedInputStream bufferedInputStream = null;
        OutputStream outputStream = null;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            bufferedInputStream = new BufferedInputStream(fileInputStream);

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString());
            response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            int length;
            while ((length = bufferedInputStream.read(bytes)) != -1){
                outputStream.write(bytes, 0, length);
            }
            outputStream.flush();
        }catch (Exception e){
            log.error("文件下载失败", e);
            return ResultData.error("文件下载失败");
        }finally {
            try {
                if (bufferedInputStream != null){
                    bufferedInputStream.close();
                }
                if (outputStream != null){
                    outputStream.close();
                }
                if (fileInputStream != null){
                    fileInputStream.close();
                }
            }catch (IOException e){
                log.error(e.getMessage(), e);
            }
        }
        return ResultData.error("下载成功");
    }

}
